#! /bin/bash

## file: steal_ipmac.sh
## auther: huanlf@gmail.com
## steal an "valid" ip and mac and connect to net :)

IFACE='eth0'
LOGFILE='/tmp/ipmac.log'
MACFILE='/home/huan/mydoc/mac'
DEFAULT_IP='192.168.1.106'
DEFAULT_MAC='00:1A:A0:53:93:F6'
DEFAULT_GW='192.168.1.1'
DEFAULT_TESTIP='220.181.38.84'

## configure ip,mac,default gw
change_ipmac()
{
    local ip=$1
    local mac=$2

    ifconfig "$IFACE" 0 down
    ifconfig "$IFACE" hw ether "$mac"
    ifconfig "$IFACE" "$ip" up

    if ! netstat -nr | grep -wq '^0.0.0.0 '; then
        route add default gw "$DEFAULT_GW"
    fi
}

## configure interface with default ip,mac
change_default()
{
    change_ipmac "$DEFAULT_IP" "$DEFAULT_MAC"
}

## test if the ip is being on line
do_arping()
{
    local ip=$1
    arping -fw1 "$ip" &>/dev/null

    return $?
}

## test if we can connect to internet by ping
do_ping()
{
    ping -w2 -c1 "$DEFAULT_TESTIP" &>/dev/null

    return $?
}

get_current_ip()
{
    ifconfig "$IFACE" | awk -F: '/inet addr:/ { print $2 }' | awk '{ print $1 }'
}

get_current_mac()
{
    ifconfig "$IFACE" | awk '{ print $NF; exit }'
}

## ---------------main---------------- ##

if (( $UID != 0 )); then
    echo "root privilege needed"
    exit 1
fi

## if interface is not configured yes, initialize it and exit
if ! ifconfig "$IFACE" | grep -Fq 192.168.1 || [[ ! -s "$MACFILE" ]]; then
    change_default
    exit
fi

## try to choose an ip that not online
while read ip mac; do
    ifconfig "$IFACE" | grep -Fwq $ip && continue
    if ! do_arping "$ip"; then
        change_ipmac "$ip" "$mac";
        if do_ping; then
            echo "$ip $mac $( date '+%F %T' )" >> "$LOGFILE"
            exit
        fi
    fi
done < "$MACFILE"

## if all ips in db are online, choose an random one
cnt=$( wc -l < "$MACFILE" )
while :; do
    randnum=$( perl -le '$seed = shift; print int( 1 + rand($seed) ) ' $cnt )
    
    ipmac=$( sed -n "$randnum p" "$MACFILE" )
    change_ipmac $ipmac
    if do_ping; then
        echo "$ip $mac $( date '+%F %T' )" >> "$LOGFILE"
        break
    fi
done
